<?php


namespace app\api\controller\v1;

use app\middleware\ApiAuth;
use think\facade\Validate;
use think\Request;
use think\validate\ValidateRule;
use think\response\Json;
use app\api\model\UserModel;
use think\facade\Db;
use think\facade\Cache;
class Login
{
    protected $middleware = [ApiAuth::class];
    
    /** 用户、司机登录
     * @param Request $request
     * @return Json
     */
    public function login(Request $request)
    {
        // 接收参数
        $input['phone'] = $request->post('phone'); // 手机号
        $input['vcode'] = $request->post('vcode'); // 验证码
        $input['account'] = $request->post('account'); // 用户名
        $input['pwd'] = $request->post('pwd'); // 密码
        $input['type'] = $request->post('type'); // 类型 1：用户 2：司机 3：秤
        $input['admin_id'] = $request->post('admin_id'); // 运营商ID
        // 参数校验
        $validate = Validate::rule([
//            'phone' => ValidateRule::regex("/^[0-9a-zA-Z]{3,12}$/", '账号包含0到9小大写字母3到12位')::isRequire(),
            'pwd' => ValidateRule::regex("/^[0-9a-zA-Z]{3,12}$/", '密码包含0到9小大写字母3到12位')::isRequire(),
            'type'=>ValidateRule::isRequire(),
            'admin_id'=>ValidateRule::isRequire(),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        if($input['vcode']&& empty($input['pwd'])){
            $server_code =  Cache::store('redis')->handler()->get('A' . $input['phone']);
            if($server_code!=$input['vcode']) return jsonFail('验证码不正确');
        }
        // 逻辑处理
        return UserModel::login($input);
    }
    /** 用户注册
     * @param Request $request
     * @return Json
     */
    public function register(Request $request)
    {
        // 接收参数
        $input['openid'] = $request->post('openid'); //微信openid
        $input['admin_id'] = $request->post('admin_id'); //运营商ID
        $input['code'] = $request->post('code'); // 邀请码
        $input['name'] = $request->post('name'); // 姓名
        $input['vcode'] = $request->post('vcode'); // 验证码
        $input['phone'] = $request->post('phone'); // 账号
        $input['pwd'] = $request->post('pwd'); // 密码
        $input['addpassword'] = $request->post('addpassword');
        $input['group_name'] = $request->post('group_name'); // 公司名称
        $input['role_type'] = $request->post('role_type'); // 类型 1：老板 2：员工
        // 参数校验
        $validate = Validate::rule([
            'admin_id'=>ValidateRule::isRequire(),
            'openid'=>ValidateRule::isRequire(),
            'phone' => ValidateRule::regex("/^[0-9a-zA-Z]{3,12}$/", '账号包含0到9小大写字母3到12位')::isRequire(),
            'pwd' => ValidateRule::regex("/^[0-9a-zA-Z]{3,12}$/", '密码包含0到9小大写字母3到12位')::isRequire(),
            'role_type'=>ValidateRule::isRequire(),
            'name'=>ValidateRule::isRequire(),
            'vcode'=>ValidateRule::isRequire(),
            'group_name'=>ValidateRule::isRequire(),
            'addpassword' => function($value,$all) {
                if ($value === null) {
                    return '缺少参数';
                } elseif ($value != $all['pwd']) {
                    return '两次输入密码不一致!';
                } else {
                    return true;
                }
            },
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        $server_code =  Cache::store('redis')->handler()->get('Z' . $input['phone']);
        if($server_code!=$input['vcode']) return jsonFail('验证码不正确');
        // 逻辑处理
        return UserModel::register($input);
    }
    /**发送短信
     * @return mixed
     */
    public function SendMsg(Request $request)
    {
        if (!request()->isPost()) return app('json')->fail('请采用正确的方式登录!');
        $phone = $request->param('phone');//手机号码
        $type = $request->param('type');//注册加Z，忘记密码加Y，登录加A，学校管理人员加A
        $code = substr(microtime(), -6);// 验证码
        $expire = 3; // 验证码有效时间
        try {
            $res =  Cache::store('redis')->handler()->get($type . $phone);//注册加Z，忘记密码加Y
            if($res) return jsonFail('验证码暂未过期，请勿重新发送');
            $res =   json_decode(Send_msg('tx',$phone,'template1',['code' =>$code,'expire' =>$expire]),true);
            if ($res['code'] == 200) {
                $res =  Cache::store('redis')->handler()->set($type . $phone, $code, 60 * $expire);//注册加Z，忘记密码加Y
                if ($res != 0) return jsonSuccess('发送成功');
                return jsonFail('发送失败');
            } else {
                return jsonFail('发送失败');
            }
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }
    /**修改密码
     * @param Request $request
     */
    public function ChangePwd(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $type = $request->param('type');//1:用户 2：商户
        $phone = $request->param('phone');//手机号码
//        $account = $request->param('account');//用户名
        $code = $request->param('code');//验证码
        $pwd = $request->param('pwd');//一次次密码
        $ckpwd = $request->param('ckpwd');//二次密码
        if (is_null($type) || empty($phone) || empty($code) || empty($pwd) || empty($ckpwd)) return jsonFail('缺少参数');
        try {
            $res =  Cache::store('redis')->handler()->get('Y' . $phone);
            if (empty($res)) return jsonFail('验证码已过期，请重新获取');
            if ($res != $code) return jsonFail('验证码不正确');
            if ($pwd != $ckpwd) return jsonFail('密码不一致');
            if ($type == 1) {
                $res = Db::table('eb_user')->where('phone', $phone)->update(['pwd' => sha1($pwd)]);
            } else {
                $res = Db::table('eb_store')->where('bank_phone', $phone)->update(['pwd' => sha1($pwd)]);
            }
            if ($res != 0) return jsonSuccess('重置成功！');
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }
    /**注销登陆
     * @return mixed
     */
    public function LoginOut(Request $request)
    {
        if (!request()->isPost()) return app('json')->fail('请采用正确的方式登录!');
        $token = $request->param('token');//获取token
        if (empty($token)) return jsonFail('登录失效');
        $redis = Cache::store('redis')->handler();
        $res = $redis->del($token);
        if ($res === 1) {
            return jsonSuccess('退出成功!');
        } else {
            return jsonFail('退出失败!');
        }
    }
    /**
     * 获取所有公司列表
     * @param Request $request
     */
    public function CompanyList(Request $request)
    {
        $data['list'] = Db::table('company')->field('id,name')->select()->toArray();
        return jsonSuccess('获取成功！', $data);
    }

}